package myJs.api

import myJs.myPkg.MyFetch
import org.scalajs.dom.{File, FormData, XMLHttpRequest, window}
import upickle.default.{read, write}
import org.scalajs.macrotaskexecutor.MacrotaskExecutor.Implicits._
import shared.pojo.Pojo._
import slinky.web.html.s

/**
 * Created by yz on 18/5/2022
 */
object Api {

  val apiUrl = window.location.hostname match {
    case "localhost" => "http://localhost:9000"
    case "192.168.1.110" => "http://192.168.1.110:9000"
    case _ => "http://47.92.172.28:9010"
  }

  val baseUrl=s"${Api.apiUrl}/panda/app"

  def images = {
    s"${apiUrl}/assets/images"
  }

  def login(request: Login.Request) = {
    val url = s"${Api.apiUrl}/panda/login"
    MyFetch.postRnText(url = s"${url}", data = write(request), headers = Map("Content-Type" -> "application/json")).map { str =>
      read[Login.Response](str)
    }
  }

  val sample = SampleApi

  val test = TestApi

  val wechatMember = WechatMemberApi

  val specialMember = SpecialMemberApi

  val member = MemberApi

  val companyMember = CompanyMemberApi

  val sampleId = SampleIdApi
  val freezerSet = FreezerSetApi

  def uploadFile(file: File)(f: UploadFile.Response => Unit) = {
    val url = s"${Api.apiUrl}/panda/tool/uploadFile"
    val xhr = new XMLHttpRequest
    xhr.open("post", url, false)
    xhr.onreadystatechange = (e) => {
      if (xhr.readyState == XMLHttpRequest.DONE) {
        val response = read[UploadFile.Response](xhr.responseText)
        f(response)
      }
    }
    val formData = new FormData()
    formData.append("file", file)
    xhr.send(formData)
  }

  def changePassword(request: ChangePassword.Request) = {
    val url = s"${Api.apiUrl}/panda/app/changePassword"
    MyFetch.postRnText(url = s"${url}", data = write(request),
      headers = Map("Content-Type" -> "application/json")).map { str =>
      read[ValidData](str)
    }
  }

  def accountCheck(request: AccountData) = {
    val url = s"${baseUrl}/accountCheck"
    MyFetch.postRnText(url = s"${url}", data = write(request), headers = Map("Content-Type" -> "application/json")).map { str =>
      read[ValidData](str)
    }
  }



}
